# -*- coding: utf-8 -*-
# Author zwhset

import hashlib

from flask import session, redirect
from functools import wraps

from ..db import Mysql, Redis
from google_two_step import GoogleTwoSetpAuth

from ..log import log_write
from ..log import ERROR, WARNING, INFO


def is_login(func):
    '''是否登陆的装饰器'''

    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get("username", None):
            return func(*args, **kwargs)
        return redirect("/login")

    return wrapper


class User(Mysql):
    '''User object'''

    def __int__(self):
        pass

    def check(self, user, passwd, token):
        '''
        检查用户登陆逻辑

        :param user username
        :param passwd password
        :token google two step token

        :return bool, message

        '''

        if not user or not passwd or not token:
            return False, "Params Fail, not fund user or passwd or token"

        # 容易出错代码往前提，性能
        if not token.isdigit():
            return False, "token format fail"
        token = int(token)

        query = '''
            SELECT
                username, password, token, status
            FROM 
                auth_user
            WHERE
                username = '{user}'
        '''.format(user=user)

        data = self.fetchone(query, is_dict=False)

        if not data:
            return False, "Not fund username"

        username, password, dtoken, status = data

        if not status: # is 0
            return False, "not perm access"

        # passwd to md5(passwd)
        if hashlib.md5(passwd).hexdigest() != password:
            return False, "password Fail."

        # token要处理一下
        g = GoogleTwoSetpAuth()
        dtoken = g.get_totp_token(dtoken)

        if token not in dtoken: # 30秒容错率
            return False, "token error"

        return True, "Login success"


    def add(self, username, password, wechat="",
            qq=0, email="", status=1):
        '''add user record to mysql'''

        # shutff google two step token
        g = GoogleTwoSetpAuth()
        token = g.shutff_str()

        # md5(password)
        password = hashlib.md5(password).hexdigest()

        query = '''
            INSERT INTO 
                auth_user(username, password, wechat, qq, email, token ,status)
            VALUES
                ('{username}', '{password}', '{wechat}', {qq}, '{email}', '{token}', {status})
        '''.format(username=username, password=password, wechat=wechat,
                   qq=qq, email=email, token=token, status=status)

        try:
            self.write(query)
            return True, "register successd"
        except Exception as e:
            log_write(module=User.__name__, function="add", type=ERROR, message=str(e))
            return False, "System error"

    def update(self, id, password=None, wechat=None, qq=None,
               email=None, token=None, status=None):
        '''
        更新用户信息， 给定参数则更新，
        如果给定token则重置token，
        如果status为真为激活帐号，为假则拒绝登陆

        :param id: int
        :param password: str
        :param wechat: str
        :param qq: int
        :param email: str
        :param token: bool
        :param status: bool

        :return: bool, message
        '''

        query = '''
            UPDATE 
                auth_user
            SET
                
        '''

        # 更新操作
        if password:
            query += ' password="{password}"'.format(password=password)

        if wechat:
            query += ' wechat="{wechat}"'.format(wechat=wechat)

        if qq:
            query += ' wechat="{qq}"'.format(qq=qq)

        if email:
            query += ' wechat="{email}"'.format(email=email)

        # 重置token
        if token:
            g = GoogleTwoSetpAuth()
            token = g.shutff_str()
            query += ' token="{token}"'.format(token=token)

        # 激活拒绝帐号
        if status:
            status = 1
        else:
            status = 0
        query += ' status={status}'.format(status=status)

        query += ' WHERE id={id}'.format(id=id)

        try:
            return True, self.write(query)
        except Exception as e:
            log_write(module=User.__name__, function="update", type=ERROR, message=str(e))
            return False, "System error"

    def delete(self, id):
        '''delete user'''
        if not id or not isinstance(id, int):
            return False, "id error"

        query = '''DELETE FROM auth_user WHERE id={id}'''.format(id=id)
        try:
            self.write(query)
            return True, "Delete User Success."
        except Exception as e:
            log_write(module=User.__name__, function="delete", type=ERROR, message=str(e))
            return False, "System error"

    def select(self, username=None):
        '''
        select user

        @:param username search *username*

        :return dict
        '''
        query = '''
            SELECT 
                id, username, token, wechat, qq, email, status
            FROM
                auth_user        
        '''
        if username:
            query += ' WHERE username like "%{username}%"'.format(username=username)

        query += ' ORDER BY username'

        return self.fetchall(query)